<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getAllUserService, addUserService } from '@/api/user';
import { getAllBuildingService } from '../../api/building';
import { deleteUserService, updateUserService } from '../../api/user';

const tableData = reactive([])

const search = ref('')
const filterTableData = computed(() =>
    tableData.filter(
        (data) =>
            !search.value ||
            data.name.toLowerCase().includes(search.value.toLowerCase()) || data.roomNumber.toLowerCase().includes(search.value.toLowerCase())
    )
)


const pageNum = ref(1)
const total = ref(20)
const pageSize = ref(10)

async function getUserList() {
    tableData.length = 0
    let result = await getAllUserService(pageNum.value, pageSize.value)
    if (result.code === 0) {
        total.value = result.data.total
        for (let i = 0; i < result.data.items.length; i++) {
            tableData.push(result.data.items[i])
        }
    } else {
        console.log(res.message)
    }
}
getUserList()


const onSizeChange = (size) => {
    pageSize.value = size
    getUserList()
}
const onCurrentChange = (num) => {
    pageNum.value = num
    getUserList()
}

const dialogFormVisible = ref(false)

const props = {
    expandTrigger: 'hover',
}

const options = []

const cascader = ref([])

const getAllBuilding = async () => {
    options.length = 0
    let res = await getAllBuildingService()
    let result = res.data
    // console.log(result)
    for (let i = 0; i < result.length; i++) {
        let option = { value: result[i].building, label: result[i].building + '栋', children: [] }
        for (let j = 1; j < result[i].unitCount + 1; j++) {
            option.children[j - 1] = { value: j, label: j + '单元', children: [] }
            for (let n = 1; n < result[i].floorCount + 1; n++) {
                option.children[j - 1].children[n - 1] = { value: n, label: n + '层', children: [] }
                for (let x = 1; x < result[i].roomCount + 1; x++) {
                    let temp = x < 10 ? '0' + x : x
                    option.children[j - 1].children[n - 1].children[x - 1] = { value: temp, label: temp + '室' }
                }
            }
        }
        options[i] = option
        // console.log(options)
    }
}

const openAddDialog = async () => {
    await getAllBuilding()
    dialogFormVisible.value = true
}


var addForm = reactive({
    roomNumber: '',
    name: '',
    phoneNumber: '',
    id: '',
    email: ''
})

const checkMobile = (rule, value, cb) => {
    const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
    if (regMobile.test(value)) {
        //合法的手机号
        return cb();
    }
    //手机号不合法
    cb(new Error('请输入合法的手机号！'));
}
const checkId = (rule, value, callback) => {
    const reg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(([0-2][1-9])|10|20|30|31)\d{3}(\d|X|x)$/;
    const card = reg.test(value);
    if (!card) {
        callback(new Error("身份证号格式有误！"));
    } else {
        callback();
    }
}
const rules = {
    roomNumber: [{ required: true, message: '房间号不可为空！', trigger: 'blur' }],
    name: [{ required: true, message: '姓名不可为空！', trigger: 'blur' }],
    phoneNumber: [
        { required: true, message: '手机号不可为空！', trigger: 'blur' },
        { validator: checkMobile, trigger: ['blur', 'change'] }
    ],
    email: [
        { required: true, message: '邮箱不可为空！', trigger: 'blur' }
        ,
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    id: [
        { required: true, message: '身份证号不可为空！', trigger: 'blur' },
        { validator: checkId, trigger: ['blur', 'change'] }
    ]
}

const addUser = async () => {
    addForm.roomNumber = cascader.value[0] + cascader.value[1] + cascader.value[2] + cascader.value[3]
    // console.log(addForm.roomNumber)
    await addUserService(addForm)
    ElMessage.success('新增业主成功')
    getUserList()
    cascader.value = [] 
    addForm.roomNumber = ''
    addForm.name = ''
    addForm.phoneNumber = ''
    addForm.id = ''
    addForm.email = ''
    dialogFormVisible.value = false
}


const deleteUser = async (roomNumber) => {
    await deleteUserService(roomNumber)
    ElMessage.success('删除成功')
    getUserList()
}

const updataForm = reactive({
    roomNumber: '',
    name: '',
    phoneNumber: '',
    id: '',
    email: ''
})

const updataDialogFormVisible = ref(false)

const handleEdit = (row) => {
    updataForm.roomNumber = row.roomNumber
    updataForm.name= row.name
    updataForm.phoneNumber= row.phoneNumber
    updataForm.id= row.id
    updataForm.email= row.email

    updataDialogFormVisible.value = true
}

const updataUser = async () => {
    await updateUserService(updataForm)
    ElMessage.success('修改成功')
    getUserList()
    updataDialogFormVisible.value = false
}

</script>



<template>
    <div style="width: 100%;padding:25px;">
        <div style="display: flex;padding-bottom: 20px;padding-top: 10px;">
            <el-button type="primary" @click="openAddDialog"
                style="width: 70px;background-color: rgb(19, 179, 232);color: white;">添加用户</el-button>
            <el-input v-model="search" placeholder="搜索用户信息" style="width: 200px;margin-left:100vh;" />
        </div>
        <el-table :data="filterTableData" border stripe style="min-width:calc(100vh - 200px)">
            <el-table-column label="门牌号" prop="roomNumber" sortable />
            <el-table-column label="姓名" prop="name" sortable />
            <el-table-column label="手机号" prop="phoneNumber" />
            <el-table-column label="身份证号" prop="id" />
            <el-table-column label="邮箱" prop="email" />
            <el-table-column label="操作" align="center" width='200px'>
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-popconfirm confirm-button-text="确认" cancel-button-text="取消" :icon="InfoFilled"
                            icon-color="red" title="确认要删除此业主信息吗？" @confirm="deleteUser(scope.row.roomNumber)">
                            <template #reference>
                                <el-button size="small" type="danger">删除</el-button>
                            </template>
                        </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin: 10px 0;">
            <el-pagination v-model:current-page="pageNum" v-model:page-size='pageSize' :page-sizes="[5, 10, 20]"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="onSizeChange"
                @current-change="onCurrentChange" />
        </div>
    </div>


    <el-dialog v-model="dialogFormVisible" title="新增业主信息" width="500">
        <el-form :model="addForm" label-width="90px" :rules="rules" ref="form">
            <el-form-item label="门牌号" prop="roomNumber">
                <!-- <el-input v-model="addForm.roomNumber" /> -->
                <el-cascader v-model="cascader" :options="options" :props="props" />
            </el-form-item>
            <el-form-item label="姓名" prop="name">
                <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="手机号" prop="phoneNumber">
                <el-input v-model="addForm.phoneNumber" />
            </el-form-item>
            <el-form-item label="身份证号" prop="id">
                <el-input v-model="addForm.id" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="addForm.email" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="addUser">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog v-model="updataDialogFormVisible" title="修改业主信息" width="500">
        <el-form :model="updataForm" label-width="90px" :rules="rules">
            <el-form-item label="姓名" prop="name">
                <el-input v-model="updataForm.name" />
            </el-form-item>
            <el-form-item label="手机号" prop="phoneNumber">
                <el-input v-model="updataForm.phoneNumber" />
            </el-form-item>
            <el-form-item label="身份证号" prop="id">
                <el-input v-model="updataForm.id" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="updataForm.email" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="updataDialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="updataUser">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>


</template>
